package com.msg.server;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.executor.ExecutorFilter;

/**
 * 消息服务MINA启动
 * 
 * @author 王畅
 * @since 2015年6月13日
 */
public class MinaServer {

	protected static final Logger log = LoggerFactory.getLogger(MinaServer.class);
	public static int port = 8002;

	/**
	 * 仅启动TCP监听
	 * 
	 * @author 王畅
	 * @throws IOException
	 * @throws Exception
	 */
	public static void Start() throws IOException, Exception {

		NioSocketAcceptor acceptor = new NioSocketAcceptor();
		acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 1);
		acceptor.getFilterChain().addLast("logger", new LoggingFilter());
		acceptor.getFilterChain().addLast("coder", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
		acceptor.getFilterChain().addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
		acceptor.getSessionConfig().setReceiveBufferSize(4096);
		acceptor.getSessionConfig().setReadBufferSize(4096);
		acceptor.getSessionConfig().setKeepAlive(true);
		acceptor.getSessionConfig().setTcpNoDelay(false);
		acceptor.getSessionConfig().setReuseAddress(true);
		acceptor.setHandler(new ServerHandler());
		// 服务端绑定两个端口,8001用于接收并处理TCP请求,8002用于接收并处理HTTP请求
		List<SocketAddress> socketAddresses = new ArrayList<SocketAddress>();
		socketAddresses.add(new InetSocketAddress(port));
		acceptor.bind(socketAddresses);
		log.info(" Mina Server Tcp start on port:{}", port);
	}
}
